package com.hsh.annotations.aspect;

import com.hsh.annotations.annotation.Retry;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.concurrent.atomic.AtomicInteger;

@Aspect
@Component
public class RetryAspect {
    private final Logger logger = LoggerFactory.getLogger(this.getClass().getSimpleName());

    private AtomicInteger atomicInteger = new AtomicInteger(0);

    @Pointcut("@annotation(com.hsh.annotations.annotation.Retry)")
    public void retryPointcut() {
    }

    /**
     * aop切入的重试
     */
    @Around("retryPointcut()")
//    @Transactional(isolation = Isolation.READ_COMMITTED)//事务隔离级别
    @Transactional
    public Object tryAgain(ProceedingJoinPoint joinPoint) throws Throwable {
        logger.info("开始重试注解");
        try {
            MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
            Retry retry = methodSignature.getMethod().getAnnotation(Retry.class);

            if (atomicInteger.intValue() < retry.value()) {
                int i = atomicInteger.incrementAndGet();
                System.out.println(i);
                Thread.sleep(retry.sleep() * i);
                System.out.println("开始重试第" + i + " 次 ");
//                MethodInvocationProceedingJoinPoint methodPoint = ((MethodInvocationProceedingJoinPoint) joinPoint);
//              return methodPoint.proceed();
                return joinPoint.proceed();
            }
        } catch (Throwable throwable) {
            tryAgain(joinPoint);
        }
        return joinPoint.proceed();
    }
}
